package com.haidechizi.longpolling.event.listener;

import com.haidechizi.longpolling.event.Event;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wangdejun
 * @create 2021/2/24 13:41
 */
public class EventDispatcher {

    private EventDispatcher() {

    }

    private static final Map<Class<? extends Event>, List<EventListener>> listenerHolder = new ConcurrentHashMap<>();

    public static final void addListener(Class<? extends Event> clazz, EventListener listener) {
        List<EventListener> listeners;
        // 非线程安全，需要使用synchronized
        synchronized (EventDispatcher.class) {
            if (listenerHolder.containsKey(clazz)) {
                listeners = listenerHolder.get(clazz);
            } else {
                listeners = new ArrayList<>();
                listenerHolder.put(clazz, listeners);
            }
        }
        listeners.add(listener);
    }

    public static final List<EventListener> getListeners(Class<? extends Event> clazz) {
        return listenerHolder.get(clazz);
    }

    public static final void fireEvent(Event event) {
        // 获取listener
        List<EventListener> listeners = listenerHolder.get(event.getClass());
        if (!CollectionUtils.isEmpty(listeners)) {
            listeners.forEach(listener -> listener.onEvent(event));
        }
    }
}
